package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.MailHelper;
import sk.naive.talker.adapter.TagConsts;
import sk.naive.talker.message.*;
import sk.naive.talker.callback.*;
import sk.naive.talker.util.Utils;

import javax.mail.*;
import javax.mail.internet.*;
import java.rmi.RemoteException;

/**
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.11 $ $Date: 2007-05-07 10:34:20 $
 */
public class MailSend extends AbstractCommand {
	public void exec()
		throws CommandException,
		RemoteException
	{
		try {
			if (params == null || params.length() == 0) {
				sendMisusageWarning();
				return;
			}
			String[] sa = Utils.splitWords(params, 2);
			String address = Utils.unquote(sa[0]);
			String subject = "";
			if (sa.length == 2) {
				subject = Utils.unquote(sa[1]);
			}
			MailHelper mailHelper = (MailHelper) getTalker().getProperties().get(MailHelper.TPROP_MAIL_HELPER);

			InternetAddress[] addresses = mailHelper.createAddresses(address);
			if (addresses == null || addresses.length == 0) {
				user.send(messageFactory().createMessage("mailSend.noAddresses", user.getProperties()));
				return;
			}
			String cId = user.setupCommandCallback(getCallback(
				user,
				addresses,
				subject,
				mailHelper
			));
			ctxSet(DefaultMessageFactory.CTXKEY_VAL, mailHelper.addressString(mailHelper.createAddresses(address)));
			sendHelper().sendLocal(user, "mailSend.begin", "editor.audienceBegin", Category.EDITOR);
			if (subject.length() > 0) {
				ctxSet(DefaultMessageFactory.CTXKEY_VAL + "Subject", subject);
				sendHelper().sendMessage(user, "mailSend.subjectLine");
			}
			user.send(Utils.tag(TagConsts.EDITOR, cId));
		} catch (MessagingException e) {
			throw new CommandException(e);
		} catch (CallbackException e) {
			throw new CommandException(e);
		}
	}

	private CommandCallback getCallback(final User user, final InternetAddress[] addresses, final String subject, final MailHelper mailHelper) {
		return new CommandCallback() {
			public Callback process(String s) throws CallbackException {
				try {
					mailHelper.sendMail(user.getLogin(), addresses, subject, Utils.unquote(s));
					sendHelper().sendLocal(user, "mailSend.successful", "editor.audienceOK", Category.EDITOR);
					return null;
				} catch (MessagingException e) {
					throw new CallbackException(e);
				} catch (RemoteException e) {
					throw new CallbackException(e);
				}
			}

			public void cancel() {
				try {
					sendHelper().sendLocal(user, "mailSend.cancelled", "editor.audienceCancel", Category.EDITOR);
				} catch (RemoteException e) {
					// ignore
				}
			}
		};
	}

	protected MessageSendHelper sendHelper() {
		return super.sendHelper();
	}
}
